# app/routes/classes.py

from flask import Blueprint, render_template, request, redirect, url_for, flash, jsonify
from app.models.models import Classes, Courses, Users
from app import db
from flask_login import current_user
from sqlalchemy import text
classes = Blueprint('classes', __name__)


# @classes.route('xxxx')   这个xxx路径仅仅为 浏览器的路径，和路由无关，所以可以随便写，但是不能有/，否则会报错。
# 而蓝图 classes.yyyy       这个才是前端要调用的路由


# 列出所有班级
@classes.route('/classes')
def list_classes():
    current_user_id = current_user.id
    current_user_role = current_user.role

    if current_user_role == 'student':
        result = db.session.execute(text("""
                    SELECT 
                        classes.id, 
                        classes.name, 
                        courses.name AS course_name, 
                        users.username AS teacher_name
                    FROM 
                        classes
                    JOIN 
                        courses ON classes.course_id = courses.id
                    JOIN 
                        users ON classes.teacher_id = users.id
                    join 
                        sc on sc.class_id = classes.id
                    where
                        sc.student_id = :current_user_id
                """),
                                            {'current_user_id': current_user_id}
                                            )
        classes = result.fetchall()
        return render_template('classes/list.html',
                               classes=classes,
                               role=current_user.role)
    elif current_user_role == 'teacher':
        result = db.session.execute(text("""
                    SELECT 
                        classes.id, 
                        classes.name, 
                        courses.name AS course_name, 
                        users.username AS teacher_name
                    FROM 
                        classes
                    JOIN 
                        courses ON classes.course_id = courses.id
                    JOIN 
                        users ON classes.teacher_id = users.id
                    where
                        classes.teacher_id = :current_user_id
            """),
                                            {'current_user_id': current_user_id}
                                            )
        classes = result.fetchall()
        return render_template('classes/list.html',
                               classes=classes,
                               role=current_user.role)
    else:
        return render_template('index.html')

# 老师开班
@classes.route('/class/establish_class', methods=['GET', 'POST'])
def establish_class():
    if request.method == 'POST':
        # 使用 request.get_json() 来解析 JSON 数据
        data = request.get_json()
        classname = data.get('className')
        coursename = data.get('courseName')

        # 查一下数据库是否存在课程
        course_result = db.session.execute(text("""
            SELECT id FROM courses WHERE name = :coursename
        """), {'coursename': coursename}).fetchone()

        if not course_result:
            # 返回 JSON 响应，告知前端课程不存在
            return jsonify({'error': '课程不存在'}), 400

        course_id = course_result.id

        # 查一下数据库是否存在同名班级
        class_result = db.session.execute(text("""
            SELECT * FROM classes WHERE name = :classname
        """), {'classname': classname}).fetchone()

        if class_result:
            # 返回 JSON 响应，告知前端班级名重复
            return jsonify({'error': '班级名重复'}), 400

        current_user_id = current_user.id  # 当前教师的工号(id)

        # 插入新的班级记录
        db.session.execute(text("""
            INSERT INTO classes (course_id, teacher_id, name) 
            VALUES (:course_id, :teacher_id, :classname)
        """), {'course_id': course_id, 'teacher_id': current_user_id, 'classname': classname})

        db.session.commit()

        return jsonify({'message': '班级创建成功'}), 200
    # 如果不是 POST 请求，返回一个适当的响应或错误信息
    return jsonify({'error': 'Invalid request method'}), 405

@classes.route('/class/new')
def new_class():
    userRole = current_user.role
    if (userRole == 'teacher'):
        return render_template('classes/establish_class.html')
    else:
        return render_template('classes/join_class.html')

# 学生加入班级
@classes.route('/class/join_class/', methods=['GET', 'POST'])
def join_class():
    if request.method == 'POST':
        userId = current_user.id
        data = request.json  # 从 JSON 数据中获取
        classId = data.get('classId')
        print("班级号", classId)

        isExistClass = db.session.execute(text("""
            select * from sc where class_id = :classId and student_id = :userId
        """), {'userId': userId, 'classId': classId}).fetchone()
        if (isExistClass):
            return jsonify({'error': '您已经加入该班级'}), 400

        if classId is None:
            return jsonify({'error': '班级号不能为空'}), 400
        db.session.execute(text("""
            insert into sc values (:userId, :classId);
        """), {'classId': classId, 'userId': userId})

        db.session.commit()
        return jsonify({'message': '加入班级成功'}), 200
    # 如果不是 POST 请求，返回一个适当的响应或错误信息
    return jsonify({'error': 'Invalid request method'}), 405

# 学生退出班级
@classes.route('/class/leave/<int:id>', methods=['POST'])
def leave_class(id):
    # 获取当前学生的ID，假设通过会话或其他方式获取
    student_id = current_user.id  # 需要实现这个函数

    # 删除与该学生和班级关联的 SC 记录
    db.session.execute(
        text("DELETE FROM sc WHERE class_id = :class_id AND student_id = :student_id"),
        {'class_id': id, 'student_id': student_id}
    )
    db.session.commit()

    flash('You have successfully left the class')
    return redirect(url_for('classes.list_classes'))

# 老师删除班级
@classes.route('/class/delete/<int:id>', methods=['POST'])
def delete_class(id):
    # 删除与该班级关联的 SC 记录
    db.session.execute(text("DELETE FROM sc WHERE class_id = :class_id"), {'class_id': id})

    # 删除班级记录
    class_ = Classes.query.get_or_404(id)
    db.session.delete(class_)
    db.session.commit()

    flash('Class deleted successfully')
    return redirect(url_for('classes.list_classes'))

@classes.route('/class/class_dashboard/<int:id>', methods=['GET', 'POST'])
def class_dashboard(id):
    userId = current_user.id
    userRole = current_user.role
    print(userId)
    print(userRole)
    if (userRole == 'teacher'):
        result = db.session.execute(
            text("select assignments.id as assignmentId, assignments.title as title, assignments.content as content, assignments.file_path as file_path, assignments.weight as weight "
                 "from assignments where :classId = class_id"), {'classId': id}
        ).fetchall()
        db.session.commit()


        return render_template('classes/class_dashboard.html', class_id=id, assignments=result, role=userRole)
    else:  # 如果是学生
        result = db.session.execute(
            text("select assignments.id as assignmentId, assignments.title as title, assignments.content as content, assignments.file_path as file_path, submissions.file_path as isSubmit, submissions.grade as isCorrect, assignments.weight "
                 "from assignments left join submissions on assignments.id = submissions.assignment_id and :userId = submissions.student_id where :classId = class_id"), {'userId': userId, 'classId': id}
        ).fetchall()
        db.session.commit()


        total_score = 0
        weight_sum = 0
        # 遍历result
        for assignment in result:
            if assignment.isCorrect is not None:  # 如果该作业已批改
                weight_sum += assignment.weight

        for assignment in result:
            if assignment.isCorrect is not None:  # 如果该作业已批改
                total_score += assignment.isCorrect * assignment.weight / weight_sum


        return render_template('classes/class_dashboard.html', class_id=id, assignments=result, role=userRole, total_score=total_score)

